package tn.orange.canreminder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import tn.orange.canreminder.adapter.MatchAdapter;
import tn.orange.canreminder.facebook.BaseDialogListener;
import tn.orange.canreminder.facebook.BaseRequestListener;
import tn.orange.canreminder.facebook.LoginButton;
import tn.orange.canreminder.facebook.SessionStore;
import tn.orange.canreminder.helper.CalendrierHelper;
import tn.orange.canreminder.helper.CompetitionHelper;
import tn.orange.canreminder.model.Competition;
import tn.orange.canreminder.model.Country;
import tn.orange.canreminder.model.Poule;
import tn.orange.canreminder.singleton.CompetitionSingleton;
import tn.orange.canreminder.singleton.CountrySingleton;
import tn.orange.canreminder.singleton.PouleSingleton;
import tn.orange.canreminder.sort.CompetitionComparator;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;

public class ListMatchActivity extends Activity implements OnClickListener {

	private ListView listView;
	private Button equipeBtn;
	private Button pouleBtn;
	private Button allBtn;
	private String[] tabCountries;
	private boolean[] bs;
	private String[] tabpoules;
	private boolean[] tp;
	public static final String APP_ID = "277789552279694";

	private Facebook mFacebook;
	private AsyncFacebookRunner mAsyncRunner;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.matchs);
		listView = (ListView) findViewById(R.id.list_match);

		equipeBtn = (Button) findViewById(R.id.equipe_btn);
		equipeBtn.setOnClickListener(this);
		pouleBtn = (Button) findViewById(R.id.groupe_btn);
		pouleBtn.setOnClickListener(this);
		allBtn = (Button) findViewById(R.id.all_btn);
		allBtn.setOnClickListener(this);
		CompetitionAsyncTask asyncTask = new CompetitionAsyncTask();
		asyncTask.execute();

	}

	public void OnFBClick(View V) {

		try {
			Facebook mFacebook = new Facebook("277789552279694");
			mAsyncRunner = new AsyncFacebookRunner(mFacebook);

			SessionStore.restore(mFacebook, this);

			LoginButton button = (LoginButton) V;
			String description = (String) V.getTag();
			button.init(this, mFacebook);

			if (APP_ID == null) {
				Util.showAlert(
						this,
						"Warning",
						"Facebook Applicaton ID must be "
								+ "specified before running this example: see Example.java");
			}

			Bundle params = new Bundle();
			params.putString("caption",
					" Vivez le CAN 2012 avec CANReminder ;)");
			params.putString("description", description);
			String HACK_ICON_URL = "http://www.kawarji.com/upl/news/logo_can_2012_01.jpg";
			params.putString("picture", HACK_ICON_URL);

			mFacebook.dialog(ListMatchActivity.this, "feed", params,
					new SampleDialogListener());
		} catch (Exception e) {
			showErrorDialog("Problème de connexion");

		}
	}

	public void OnConfigClick(View v) {
		final Competition competition = (Competition) v.getTag();
		LayoutInflater factory = LayoutInflater.from(this);
		final View alertDialogView = factory.inflate(R.layout.equipe_config,
				null);

		// Création de l'AlertDialog
		AlertDialog.Builder adb = new AlertDialog.Builder(this);

		// On affecte la vue personnalisé que l'on a crée à notre
		// AlertDialog
		adb.setView(alertDialogView);

		// On donne un titre à l'AlertDialog
		adb.setTitle("Recevoir une notification");

		// On modifie l'icône de l'AlertDialog pour le fun ;)
		adb.setIcon(android.R.drawable.ic_dialog_alert);
		final Spinner s = (Spinner) alertDialogView.findViewById(R.id.spinner);

		ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
				R.array.notif, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		s.setAdapter(adapter);

		// affecte un évènement
		adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					int min = CalendrierHelper.convertTominutes(s
							.getSelectedItem().toString());

					CalendrierHelper.saveMatchIntoCalenndar(competition,
							getApplicationContext(), min);

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
		adb.show();

	}

	private class CompetitionAsyncTask extends
			AsyncTask<Void, Void, List<Competition>> {
		private final ProgressDialog dialog = new ProgressDialog(
				ListMatchActivity.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Veuillez patienter...");
			this.dialog.setCancelable(false);
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected List<Competition> doInBackground(final Void... args) {

			List<Competition> competitions = null;
			try {
				CountrySingleton.getInstance();
				competitions = CompetitionSingleton.getInstance();
				if (competitions.size() == 0)
					throw new NullPointerException();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				cancel(false);
			}
			return competitions;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}

			showErrorDialog("Problème de connexion ");

		}

		// can use UI thread here
		protected void onPostExecute(List<Competition> competitions) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
				CompetitionComparator comparator = new CompetitionComparator();
				Collections.sort(competitions, comparator);

				MatchAdapter adapter = new MatchAdapter(ListMatchActivity.this,
						competitions);
				listView.setAdapter(adapter);

			}
		}
	}

	private void showErrorDialog(String message) {
		AlertDialog alertDialog = new AlertDialog.Builder(
				ListMatchActivity.this).create();
		alertDialog.setTitle("Erreur");
		alertDialog.setMessage(message);
		alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				ListMatchActivity.this.finish();
			}
		});

		alertDialog.show();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == equipeBtn) {

			List<Country> countries;
			try {
				countries = CountrySingleton.getInstance();
				tabCountries = new String[countries.size()];
				int i = 0;
				for (Country country : countries) {
					tabCountries[i] = country.getName();
					i++;
				}

				bs = new boolean[tabCountries.length];

				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("choix");

				builder.setMultiChoiceItems(tabCountries, bs,
						new OnMultiChoiceClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which, boolean isChecked) {

							}
						});

				builder.setPositiveButton("Ok",
						new android.content.DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub

								List<String> values = new ArrayList<String>();
								int i = 0;
								for (Boolean val : bs) {
									if (val == true)
										values.add(tabCountries[i]);
									i++;
								}

								List<Competition> competitions;
								try {
									competitions = CompetitionSingleton
											.getInstance();
									List<Competition> newCompetitions = CompetitionHelper
											.getCompetitionbyEquipe(values,
													competitions);

									MatchAdapter adapter = new MatchAdapter(
											ListMatchActivity.this,
											newCompetitions);
									listView.setAdapter(adapter);
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

							}
						});
				AlertDialog alert = builder.create();
				alert.show();
			} catch (Exception e1) {
				showErrorDialog("Problème de connexion");
			}

		} else if (v == pouleBtn) {
			List<Poule> poules;
			try {
				poules = PouleSingleton.getInstance();
				tabpoules = new String[poules.size()];
				int i = 0;
				for (Poule poule : poules) {
					tabpoules[i] = poule.getName();
					i++;
				}

				tp = new boolean[tabpoules.length];

				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("Poule :");

				builder.setMultiChoiceItems(tabpoules, tp,
						new OnMultiChoiceClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which, boolean isChecked) {

							}
						});

				builder.setPositiveButton("Ok",
						new android.content.DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub

								List<String> values = new ArrayList<String>();
								int i = 0;
								for (Boolean val : tp) {
									if (val == true)
										values.add(tabpoules[i]);
									i++;
								}

								List<Competition> competitions;
								try {
									competitions = CompetitionSingleton
											.getInstance();
									List<Competition> newCompetitions = CompetitionHelper
											.getCompetitionbyPoule(values,
													competitions);

									MatchAdapter adapter = new MatchAdapter(
											ListMatchActivity.this,
											newCompetitions);
									listView.setAdapter(adapter);
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

							}
						});
				AlertDialog alert = builder.create();
				alert.show();
			} catch (Exception e1) {
				showErrorDialog("Problème de connexion");
			}

		} else if (v == allBtn) {
			List<Competition> competitions;
			try {
				competitions = CompetitionSingleton.getInstance();
				MatchAdapter adapter = new MatchAdapter(ListMatchActivity.this,
						competitions);
				listView.setAdapter(adapter);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	public class WallPostDeleteListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			if (response.equals("true")) {
				Log.d("Facebook-Example", "Successfully deleted wall post");
				ListMatchActivity.this.runOnUiThread(new Runnable() {
					public void run() {

					}
				});
			} else {
				Log.d("Facebook-Example", "Could not delete wall post");
			}
		}
	}

	public class WallPostRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			Log.d("Facebook-Example", "Got response: " + response);
			String message = "<empty>";
			try {
				JSONObject json = Util.parseJson(response);
				message = json.getString("message");
			} catch (JSONException e) {
				Log.w("Facebook-Example", "JSON Error in response");
			} catch (FacebookError e) {
				Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
			}
			final String text = "Your Wall Post: " + message;
			ListMatchActivity.this.runOnUiThread(new Runnable() {
				public void run() {

				}
			});
		}
	}

	public class SampleDialogListener extends BaseDialogListener {

		public void onComplete(Bundle values) {
			final String postId = values.getString("post_id");
			if (postId != null) {
				Log.d("Facebook-Example", "Dialog Success! post_id=" + postId);
				mAsyncRunner.request(postId, new WallPostRequestListener());

			} else {
				Log.d("Facebook-Example", "No wall post made");
			}
		}
	}

	public void OnHomeClick(View v) {
		Intent intent = new Intent(getApplicationContext(),
				DashboardActivity.class);
		startActivity(intent);
	}
}
